package com.shopping.www.controller;


import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
* 替换HttpServlet，根据请求的最后一段路径来进行方法转发*/

@WebServlet("/baseServlet")
public class BaseServlet extends HttpServlet {

    //根据请求的最后一段路径来进行方法转发
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求路径
        String uri=request.getRequestURI();//获取的uri是“/shopping/user/selectById”
//        System.out.println(uri);//获取的uri是“/shopping/user/selectById”
        //2.获取最后一段路径，即方法名
        int index=uri.lastIndexOf('/');
        String methodName=uri.substring(index+1);
//        System.out.println(methodName);//获取方法名
        //3.执行方法
        //3.1获取UserServlet字节码对象
        Class<? extends BaseServlet> cls=this.getClass();
        //3.2获取方法Method对象
        try {
            Method method= cls.getMethod(methodName,HttpServletRequest.class, HttpServletResponse.class);
            //3.3执行方法
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e){
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}
